import { useEffect, useState, useCallback } from 'react';
import { Row, Col, Tag, Divider, Skeleton } from 'antd';
import { MONEY_UNIT } from '@/config';

import useDevice, { DEVICES } from '@/hooks/useDevice';
import styles from './index.module.scss';

export default ({dataSource={}}) => {
    const initState = () => ({});
    const [state, setState] = useState(initState);
    const isMobile = useDevice() === DEVICES.MOBILE;

    // 域名提取（不带协议/端口/路径）
    const getDomain = useCallback((raw='') => {
        if (!raw || typeof raw !== 'string') return '';
        const s = raw.trim();
        const match = s.match(/^(?:https?:\/\/)?([^\/?#:]+)(?:[\/?#:]|$)/i);
        return match ? match[1] : '';
    }, []);

    // 规范化链接（缺协议时默认 https://）
    const normalizeUrl = useCallback((raw='') => {
        if (!raw) return '';
        const trimmed = raw.trim();
        if (!/^https?:\/\//i.test(trimmed)) {
            return `https://${trimmed}`;
        }
        return trimmed;
    }, []);

    // 宽松判断是否为链接
    const isUrl = useCallback((str='') => {
        if (typeof str !== 'string') return false;
        const trimmed = str.trim();
        if (!trimmed) return false;

        let urlToTest = trimmed;
        if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) urlToTest = 'http://' + trimmed;

        try {
        const url = new URL(urlToTest);
        if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
        const host = url.hostname;
        if (!host) return false;

        // 👇 关键改进：要求 hostname 至少包含一个点（排除 'aaaa', 'localhost' 等）
        if (!host.includes('.')) return false;

        return true;
        } catch {
        return false;
        }
    }, []);

    // 价格展示：接受 “金额:币种编码”，显示为 “金额币种中文名”（不带冒号）
    const formatPrice = useCallback((raw) => {
        if (raw === undefined || raw === null || raw === '') return '--';
        const s = String(raw).trim();
        const m = s.match(/^([^:]+):\s*(.+)$/);
        if (m) {
            const amount = m[1].trim();
            const code = m[2].trim();
            const unitLabel = MONEY_UNIT?.[code] || '';
            return unitLabel ? `${amount}${unitLabel}` : amount;
        }
        return s;
    }, []);

    return (
        <div className={styles['container']}>
            <Divider className={styles['divider']}/>
            <Row gutter={isMobile ? [0, 12] : [24, 24]}>
                <Col 
                    xs={{ span: 24, order: 2 }}
                    sm={{ span: 24, order: 2 }}
                    md={{ span: 24, order: 2 }}
                    lg={{ span: 12, order: 0 }}
                    xl={{ span: 12, order: 0 }}
                    xxl={{ span: 12, order: 0 }}
                >
                    <section className={styles['where-selled']}>
                        <h3>交易历史</h3>
                        <div className={styles['wrapper']}>
                            {
                                (dataSource?.sellingPlats || []).map((item, index) => {
                                    // item: {plat, price, date}
                                    const linkable = isUrl(item?.plat || '');
                                    const href = linkable ? normalizeUrl(item?.plat || '') : '';
                                    const domain = linkable ? getDomain(href) : '';
                                    return (
                                        <div key={index} className={styles['item']}>
                                            <div>
                                                <span style={{paddingRight:4}}>{`${index<9?'0':''}${index+1}`}.</span>
                                                {linkable ? (
                                                    <a href={href} target="_blank" rel="noreferrer">{domain || href}</a>
                                                ) : (
                                                    <span>{item?.plat || ''}</span>
                                                )}
                                            </div>
                                            <div>{formatPrice(item?.price)}</div>
                                            <div>{item?.date ? `${item.date} 年` : '--'}</div>
                                        </div>
                                    )
                                })
                            }
                            { (dataSource?.sellingPlats || []).length ? null : <p className={styles['empty']}>暂无数据</p> }
                        </div>
                    </section>
                </Col>
                <Col 
                    xs={{ span: 24, order: 1 }}
                    sm={{ span: 24, order: 1 }}
                    md={{ span: 24, order: 1 }}
                    lg={{ span: 12, order: 0 }}
                    xl={{ span: 12, order: 0 }}
                    xxl={{ span: 12, order: 0 }}
                >
                    <section className={styles['where-sell']}>
                        <h3>这能买到</h3>
                        <div className={styles['wrapper']}>
                            {
                                (dataSource?.sellingAddresses||[]).map((item, index) => {
                                    const linkable = isUrl(item || '');
                                    const href = linkable ? normalizeUrl(item || '') : '';
                                    const domain = linkable ? getDomain(href) : '';
                                    return linkable ? (
                                        <a key={index} className={styles['a']} href={href} target="_blank" rel="noreferrer">{domain || href}</a>
                                    ) : (
                                        <span key={index} className={styles['item']}>{item || ''}</span>
                                    )
                                })
                            }
                            { (dataSource?.sellingAddresses||[]).length ? null : <p className={styles['empty']}>暂无数据</p> }
                        </div>
                    </section>
                </Col>
            </Row>
        </div>
    )
}
